import { NoticeEnum } from '@/enums';
import { api } from '@/services/api';
import { NoticeItem } from '@/services/type';
import { defineStore } from 'pinia';
import { reactive, ref } from 'vue';

import { useUserStore } from './user';

export const useNoticeStore = defineStore('notice', () => {

    const userStore = useUserStore();

    // 是否打开通知提醒框
    const isOpenNoticeBox = ref(false);
    // 通知数据
    const noticeData = ref<NoticeItem[]>([]);
    // 数据加载参数
    const paramOptions = reactive({ isLast: false, loading: true, cursor: '' });
    // 初始化加载中
    const loadnig = ref(true);

    /**
     * 清除未读消息数
     */
    const cleaUnread = () => {
        api
        .notice
        .clearUnread()
        .then(response => {
            if(response.code === 0) {
                if(userStore.userInfo.tj_info) {
                    userStore.userInfo.tj_info.notice_num = 0;
                }
            }
        });
    }

    /**
     * 加载通知提醒列表
     * @param refresh 
     */
    const getNoticePage = async (type: NoticeEnum, refresh = false) => {
        if (!refresh && paramOptions.isLast) return;
        // 获取通知提醒列表
        const response = await api
            .notice
            .getNoticePage({
                type,
                cursor: refresh ? undefined : paramOptions.cursor,
                pageSize: 10
            });
        if(response.code != 0) return;
        // 赋值
        const data = response.data;
        // 通知提醒列表
        noticeData.value = (refresh ? data.list : [...data.list, ...noticeData.value]);
        // 加载参数
        paramOptions.cursor = data.cursor;
        paramOptions.isLast = data.isLast;
        paramOptions.loading = false;
        loadnig.value = false;
    }

    /**
     * 推送通知提醒信息
     * @param data 
     */
    const pushNoticeInfo = (data: NoticeItem) => {
        if(!isOpenNoticeBox.value) {
            // 通知提醒未读数加一
            userStore.userInfo.tj_info && (userStore.userInfo.tj_info.notice_num += 1);
            return;
        }
        // 清除通知提醒未读消息数
        cleaUnread();
        noticeData.value.unshift(data);
    }

    return {
        loadnig,
        noticeData,
        isOpenNoticeBox,
        paramOptions,
        cleaUnread,
        getNoticePage,
        pushNoticeInfo
    }

});